//
//  SegBtnView.m
//  碎片切换器封装
//
//  Created by 黄星 on 15/4/28.
//  Copyright (c) 2015年 qingfanqie. All rights reserved.
//

#import "SegBtnView.h"

@interface SegBtnView ()

@property (nonatomic, strong) UIView *vBtnLine;

@property (nonatomic, assign) NSInteger cnt;
@end

@implementation SegBtnView


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.backgroundColor = [UIColor lightGrayColor];
        _vBtnLine = [[UIView alloc] init];
        _vBtnLine.backgroundColor = [UIColor redColor];
        [self addSubview:_vBtnLine];
    }
    return self;
}

// 假设宽为 320， btn 长度确认为 100；   算距离 (320 - 3 * 100 ) / 4
- (void)setSegBtnViewWithBtnName:(NSArray *)nameArr AndBtnIndex:(BtnBlock)block
{
    _senderBlock = block;
    _cnt = nameArr.count;
    for (NSInteger i = 0; i < nameArr.count; i++)
    {
        /**
         *  长度X
         */
        CGFloat btnX = (CGRectGetWidth(self.frame) - nameArr.count * 100) / (nameArr.count + 1);
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

        NSLog(@"%f",btnX * (i + 1) + 100 * i);
        btn.frame = CGRectMake(btnX * (i + 1) + 100 * i, 0, 100, CGRectGetHeight(self.frame));
        
        //btn.backgroundColor = [UIColor redColor];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitle:nameArr[i] forState:UIControlStateNormal];
        if (i == 0)
        {            
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            CGRect btnRect = btn.frame;
            btnRect.origin.y = btnRect.size.height - 3;
            btnRect.size.height = 3;
            _vBtnLine.frame = btnRect;
        }
        
        btn.tag = i + 1000;
        [btn addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [self addSubview:btn];
    }
}

- (void)onClick:(UIButton *)sender
{
    _senderBlock(sender.tag);
    
    for (NSInteger i = 1000; i < _cnt + 1000; i++)
    {
        UIButton *tagBtn = (UIButton *)[self viewWithTag:i];
        [tagBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    
    // 得到当前的Btn
    UIButton *senderBtn = (UIButton *)[self viewWithTag:sender.tag];
    [senderBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    
    CGRect lineRect = senderBtn.frame;
    lineRect.origin.y = lineRect.size.height - 3;
    lineRect.size.height = 3;
    [UIView animateWithDuration:0.2 animations:^{
        _vBtnLine.frame = lineRect;
    }];
}

@end
